﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using SocialNetwork.Models;
using System.Collections.Specialized;
using SocialNetwork;

public class aRoleProvider : RoleProvider
{

    private UserRepository _repository;

    public UserRepository repository
    {
        get { return _repository ?? (_repository = new UserRepository()); }
    }

    public override string ApplicationName
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        return repository.db.User.Where(x => x.Username == usernameToMatch && x.Role.Name == roleName).
            Select(x => x.Username).ToArray();
    }

    public override string[] GetAllRoles()
    {
        return repository.db.Role.Select(x => x.Name).ToArray();
    }

    public string GetRoleForUser(string username)
    {
        Role role = this.repository.GetRoleForUser(username);
        if (!this.repository.RoleExists(role))
            return string.Empty;

        return role.Name;
    }

    public override string[] GetRolesForUser(string username)
    {
        Role role = this.repository.GetRoleForUser(username);
        if (!this.repository.RoleExists(role))
            return new string[] { string.Empty };

        return new string[] { role.Name };
    }

    public override string[] GetUsersInRole(string roleName)
    {
        var users = repository.db.User.Where(x => x.Role.Name == roleName).Select(x => x.Username);
        return users.ToArray();
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        User user = repository.GetUser(username);

        Role role = repository.GetRole(roleName);

        if (!repository.UserExists(user.Username))
            return false;
        if (!repository.RoleExists(role))
            return false;

        return user.RoleId == role.Id;


    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        throw new NotImplementedException();
    }

    public override bool RoleExists(string roleName)
    {
        throw new NotImplementedException();
    }

    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        throw new NotImplementedException();
    }

    public override void CreateRole(string roleName)
    {
        throw new NotImplementedException();
    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        throw new NotImplementedException();
    }
}